import { defineStore } from 'pinia'
import {
  reqResourcePages,
  getResourceCategoryAll,
  reqSaveOrUpdate,
  type TCondition,
  type TQueriedResult,
  type ResourceCategoryItem,
  type TPResource
} from '@/api/resources'

export const useResourceStore = defineStore('resource', () => {
  // 查询条件 给默认值
  const queryCondition = reactive<TCondition>({
    name: '',
    url: '',
    categoryId: '',
    current: 1,
    size: 10
  })
  // 查询结果 有默认值
  const queryResult = ref<TQueriedResult>({
    current: 1,
    records: [],
    size: 1,
    total: 0
  })
  // 根据查询条件获取数据并存储为资源结果
  const queryResources = async (params: TCondition = {}) => {
    // 查询条件和默认查询条件合并
    Object.assign(queryCondition, params)
    const { data } = await reqResourcePages(queryCondition)
    if (data.code === '000000') {
      queryResult.value = data.data
    } else {
      ElMessage.error('获取资源失败！')
      throw new Error('获取资源失败！')
    }
  }
  // 增 保存或更新资源
  const saveOrUpdateResource = async (resource: TPResource) => {
    const { data } = await reqSaveOrUpdate(resource)
    if (data.code === '000000') {
      ElMessage.success('资源提交成功！')
    } else {
      ElMessage.error('资源提交失败！')
      throw new Error('资源提交失败！')
    }
  }

  // 获取All资源分类表
  const allResourcesCategory = ref<ResourceCategoryItem[]>([])

  const getAllResourcesCategory = async () => {
    const { data } = await getResourceCategoryAll()
    if (data.code === '000000') {
      allResourcesCategory.value = data.data
    } else {
      ElMessage.error('获取资源分类失败！')
      throw new Error('获取资源分类失败！')
    }
  }

  return { queryCondition, queryResult, allResourcesCategory, queryResources, getAllResourcesCategory, saveOrUpdateResource }
})
